<template>
  <div class="product-container-wrapper">
    <div class="product-container">
      <h1 class="text-2xl font-bold mb-6">商品管理</h1>
      
      <div v-if="loading" class="flex justify-center py-8">
        <el-loading :fullscreen="false" />
      </div>
      
      <div v-else>
        <!-- 搜索和过滤 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div class="flex flex-col md:flex-row md:items-center space-y-4 md:space-y-0 md:space-x-4">
            <div class="flex-1">
              <el-input 
                v-model="searchKeyword" 
                placeholder="搜索商品名称" 
                prefix-icon="el-icon-search"
                clearable
                @keyup.enter="handleSearch"
              />
            </div>
            
            <div class="flex space-x-4">
              <el-select 
                v-model="selectedCategory" 
                placeholder="选择分类" 
                clearable 
                @change="fetchProducts"
                style="min-width: 150px;"
                :loading="categoryLoading">
                <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              
              <el-button type="primary" @click="handleShowAddDialog">添加商品</el-button>
            </div>
          </div>
        </div>
        
        <!-- 商品列表 -->
        <el-table 
          :data="products" 
          border 
          style="width: 100%" 
          v-loading="tableLoading"
          :max-height="tableHeight"
          class="product-table">
          <el-table-column type="index" width="50" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <img :src="scope.row.image" style="width: 80px; height: 80px; object-fit: cover;" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="categoryName" label="分类" width="120" />
          <el-table-column prop="price" label="价格" width="120">
            <template #default="scope">
              <span class="text-red-500">¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="80" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                {{ scope.row.status === 1 ? '上架' : '下架' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row.id)"
              >删除</el-button>
              <el-button 
                type="success" 
                size="small" 
                @click="handleStartGroupBuy(scope.row)"
              >发起团购</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="flex justify-center mt-6">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <!-- 添加/编辑商品对话框 -->
      <el-dialog
        :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
        v-model="dialogVisible"
        width="600px"
      >
        <el-form :model="productForm" label-width="100px" :rules="rules" ref="productFormRef">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="productForm.name" />
          </el-form-item>
          
          <el-form-item label="商品分类" prop="categoryId">
            <el-select 
              v-model="productForm.categoryId" 
              placeholder="选择分类" 
              style="width: 100%"
              :loading="categoryLoading">
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <div v-if="categories.length === 0" class="mt-2 text-orange-500 text-sm">
              提示：未找到任何分类，请先添加分类
            </div>
          </el-form-item>
          
          <el-form-item label="商品价格" prop="price">
            <el-input-number v-model="productForm.price" :precision="2" :min="0" style="width: 100%" />
          </el-form-item>
          
          <el-form-item label="商品原价" prop="originalPrice">
            <el-input-number v-model="productForm.originalPrice" :precision="2" :min="0" style="width: 100%" />
          </el-form-item>
          
          <el-form-item label="商品库存" prop="stock">
            <el-input-number v-model="productForm.stock" :min="0" :precision="0" style="width: 100%" />
          </el-form-item>
          
          <el-form-item label="商品图片" prop="image">
            <div class="flex flex-col gap-2">
              <el-upload
                class="image-uploader"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleFileChange"
                :before-upload="beforeImageUpload"
              >
                <template v-if="productForm.image">
                  <div class="image-preview-container">
                    <img :src="productForm.image" class="product-image-preview">
                  </div>
                </template>
                <template v-else>
                  <div class="image-uploader-empty">
                    <el-icon size="30"><Plus /></el-icon>
                    <span class="mt-2">点击上传图片</span>
                    <div class="mt-3">
                      <el-button type="primary" size="small">选择图片</el-button>
                    </div>
                  </div>
                </template>
              </el-upload>
              <div v-if="productForm.image" class="flex justify-between items-center mt-2">
                <span class="text-gray-500 text-sm">已上传图片</span>
                <el-button type="danger" size="small" @click="resetImage">删除图片</el-button>
              </div>
              <div v-else class="text-gray-500 text-sm mt-2">请上传商品图片</div>
            </div>
          </el-form-item>
          
          <el-form-item label="商品描述" prop="description">
            <el-input v-model="productForm.description" type="textarea" rows="4" />
          </el-form-item>
          
          <el-form-item label="商品状态" prop="status">
            <el-switch
              v-model="productForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="上架"
              inactive-text="下架"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <div class="flex justify-end">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmitForm" :loading="submitLoading">确定</el-button>
          </div>
        </template>
      </el-dialog>
      
      <!-- 发起团购对话框 -->
      <el-dialog
        title="发起团购活动"
        v-model="groupBuyDialogVisible"
        width="500px"
      >
        <el-form :model="groupBuyForm" label-width="100px" :rules="groupBuyRules" ref="groupBuyFormRef">
          <el-form-item label="商品名称">
            <span>{{ groupBuyForm.productName }}</span>
          </el-form-item>
          
          <el-form-item label="团购价格" prop="groupPrice">
            <el-input-number 
              v-model="groupBuyForm.groupPrice" 
              :precision="2" 
              :min="0" 
              style="width: 100%" 
            />
          </el-form-item>
          
          <el-form-item label="最低人数" prop="minCount">
            <el-input-number 
              v-model="groupBuyForm.minCount" 
              :min="2" 
              :precision="0" 
              style="width: 100%" 
            />
          </el-form-item>

          <el-form-item label="每人限购" prop="limitPerUser">
            <el-input-number 
              v-model="groupBuyForm.limitPerUser" 
              :min="1" 
              :precision="0" 
              style="width: 100%" 
            />
          </el-form-item>
          
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="groupBuyForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 100%"
              :disabled-date="(time) => disabledDate(time, 'start')"
              :disabled-time="(date) => disabledTime(date, 'start')"
            />
          </el-form-item>

          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="groupBuyForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 100%"
              :disabled-date="(time) => disabledDate(time, 'end')"
              :disabled-time="(date) => disabledTime(date, 'end')"
            />
          </el-form-item>
          
          <el-form-item label="活动描述" prop="description">
            <el-input 
              v-model="groupBuyForm.description" 
              type="textarea" 
              rows="4" 
              placeholder="请输入团购活动描述"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <div class="flex justify-end">
            <el-button @click="groupBuyDialogVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="handleSubmitGroupBuy" 
              :loading="submitGroupBuyLoading"
            >确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

// 状态变量
const loading = ref(false)
const tableLoading = ref(false)
const submitLoading = ref(false)
const categoryLoading = ref(false)
const searchKeyword = ref('')
const selectedCategory = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const products = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' or 'edit'
const productFormRef = ref(null)
const tableHeight = ref(600) // 默认表格高度

// 团购相关状态
const groupBuyDialogVisible = ref(false)
const submitGroupBuyLoading = ref(false)
const groupBuyFormRef = ref(null)

// 动态计算表格高度
const updateTableHeight = () => {
  nextTick(() => {
    // 计算可用的窗口高度并考虑其他元素的高度
    // 考虑到头部、筛选区域、分页等元素的高度
    const windowHeight = window.innerHeight;
    // 预留其他元素的高度（头部、搜索栏、分页等）
    const reservedHeight = 300;
    tableHeight.value = windowHeight - reservedHeight;
    
    // 确保最小高度
    if (tableHeight.value < 400) {
      tableHeight.value = 400;
    }
  });
};

// 监听窗口大小变化
const setupResizeListener = () => {
  window.addEventListener('resize', updateTableHeight);
  // 初始计算
  updateTableHeight();
};

// 在组件卸载时移除事件监听
const cleanupResizeListener = () => {
  window.removeEventListener('resize', updateTableHeight);
};

// 获取认证令牌
const getAuthHeaders = () => {
  const token = localStorage.getItem('token')
  return {
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
  }
}

// 分类数据从后端获取
const categories = ref([])

// 获取分类数据
const fetchCategories = async () => {
  try {
    categoryLoading.value = true // 显示加载状态
    
    const response = await fetch('/api/categories', {
      headers: getAuthHeaders()
    })
    
    if (!response.ok) {
      throw new Error('获取分类列表失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '获取分类列表失败')
    }
    
    // 转换格式为下拉框需要的格式
    categories.value = (data.data || []).map(category => ({
      value: category.id.toString(),
      label: category.name
    }))
    
    // 如果没有分类，显示更明显的提示
    if (categories.value.length === 0) {
      ElMessage.warning('未找到任何分类，请先添加分类')
      // 添加一个默认选项，表示没有分类
      categories.value = [{
        value: '',
        label: '暂无分类数据'
      }]
    }
    
    // 调试日志
    console.log('加载的分类数据:', categories.value)
  } catch (error) {
    console.error('获取分类列表错误:', error)
    ElMessage.error(error.message || '获取分类列表失败，请稍后再试')
    // 加载失败时添加一个默认选项
    categories.value = [{
      value: '',
      label: '加载分类失败'
    }]
  } finally {
    categoryLoading.value = false // 隐藏加载状态
  }
}

// 商品表单
const productForm = reactive({
  id: null,
  name: '',
  categoryId: '',
  price: 0,
  originalPrice: 0,
  stock: 0,
  image: '',
  description: '',
  status: 1
})

// 图片上传相关方法
const handleFileChange = async (file) => {
  if (!file) return;
  
  try {
    const formData = new FormData();
    formData.append('file', file.raw);
    
    const response = await fetch('/api/upload', {
      method: 'POST',
      headers: {
        'Authorization': getAuthHeaders().Authorization
      },
      body: formData
    });
    
    if (!response.ok) {
      throw new Error('上传失败');
    }
    
    const data = await response.json();
    console.log('上传响应:', data);
    
    if (data.code === 200 && data.data && data.data.url) {
      // 将相对路径转换为完整的URL
      // 确保使用当前域名作为基础
      const baseUrl = window.location.origin;
      let imageUrl = data.data.url;
      
      // 处理URL
      if (imageUrl.startsWith('http')) {
        // 已经是完整URL，直接使用
        productForm.image = imageUrl;
      } else {
        // 相对路径，需要拼接
        if (imageUrl.startsWith('/')) {
          productForm.image = baseUrl + imageUrl;
        } else {
          productForm.image = baseUrl + '/' + imageUrl;
        }
      }
      
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error('图片上传失败');
    }
  } catch (error) {
    console.error('上传图片错误:', error);
    ElMessage.error('上传图片失败: ' + error.message);
  }
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  
  return true
}

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  image: [{ required: true, message: '请上传商品图片', trigger: 'blur' }]
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    tableLoading.value = true
    
    // 构建查询参数
    const params = new URLSearchParams()
    if (searchKeyword.value) {
      params.append('name', searchKeyword.value)
    }
    if (selectedCategory.value) {
      params.append('categoryId', selectedCategory.value)
    }
    params.append('pageNum', currentPage.value)
    params.append('pageSize', pageSize.value)
    
    // 调用后端API
    const response = await fetch(`/api/products?${params.toString()}`, {
      headers: getAuthHeaders()
    })
    
    if (!response.ok) {
      throw new Error('获取商品列表失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '获取商品列表失败')
    }
    
    // 更新商品列表数据，匹配后端返回的新结构
    products.value = data.data?.data || []
    total.value = data.data?.total || 0
    
    // 添加分类名称
    products.value.forEach(product => {
      const category = categories.value.find(c => c.value === product.categoryId?.toString())
      product.categoryName = category ? category.label : '未分类'
    })
    
  } catch (error) {
    console.error('获取商品列表错误:', error)
    ElMessage.error(error.message || '获取商品列表失败，请稍后再试')
  } finally {
    tableLoading.value = false
  }
}

// 搜索商品
const handleSearch = () => {
  currentPage.value = 1
  fetchProducts()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProducts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProducts()
}

// 显示添加对话框
const handleShowAddDialog = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 先重置表单，确保没有残留数据
  resetForm()
  
  // 复制除了图片以外的所有属性
  Object.keys(productForm).forEach(key => {
    if (key in row && key !== 'image') {
      productForm[key] = row[key]
    }
  })
  
  // 如果用户确实需要使用原图片，可以通过点击"选择图片"按钮重新上传
  
  dialogVisible.value = true
}

// 删除商品
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await fetch(`/api/products/${id}`, {
        method: 'DELETE',
        headers: getAuthHeaders()
      })
      
      if (!response.ok) {
        throw new Error('删除商品失败')
      }
      
      const data = await response.json()
      
      if (data.code !== 200) {
        throw new Error(data.message || '删除商品失败')
      }
      
      ElMessage.success('删除成功')
      fetchProducts()
    } catch (error) {
      console.error('删除商品错误:', error)
      ElMessage.error(error.message || '删除商品失败，请稍后再试')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 重置表单
const resetForm = () => {
  productForm.id = null
  productForm.name = ''
  productForm.categoryId = ''
  productForm.price = 0
  productForm.originalPrice = 0
  productForm.stock = 0
  productForm.image = ''
  productForm.description = ''
  productForm.status = 1
  
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
}

// 重置图片
const resetImage = () => {
  productForm.image = ''
}

// 提交表单
const handleSubmitForm = async () => {
  if (!productFormRef.value) return
  
  try {
    await productFormRef.value.validate()
    
    submitLoading.value = true
    
    const isEdit = dialogType.value === 'edit'
    const url = isEdit ? `/api/products/${productForm.id}` : '/api/products'
    const method = isEdit ? 'PUT' : 'POST'
    
    const response = await fetch(url, {
      method,
      headers: getAuthHeaders(),
      body: JSON.stringify({
        name: productForm.name,
        categoryId: productForm.categoryId,
        price: productForm.price,
        originalPrice: productForm.originalPrice,
        stock: productForm.stock,
        image: productForm.image,
        description: productForm.description,
        status: productForm.status
      })
    })
    
    if (!response.ok) {
      throw new Error(isEdit ? '更新商品失败' : '添加商品失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || (isEdit ? '更新商品失败' : '添加商品失败'))
    }
    
    ElMessage.success(isEdit ? '更新成功' : '添加成功')
    dialogVisible.value = false
    fetchProducts()
  } catch (error) {
    console.error('提交表单错误:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    submitLoading.value = false
  }
}

// 团购表单数据
const groupBuyForm = reactive({
  productId: null,
  productName: '',
  productImage: '',
  originalPrice: 0,
  groupPrice: 0,
  minCount: 2,
  limitPerUser: 1,
  startTime: '',
  endTime: '',
  description: ''
})

// 团购表单验证规则
const groupBuyRules = {
  groupPrice: [
    { required: true, message: '请输入团购价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于0', trigger: 'blur' }
  ],
  minCount: [
    { required: true, message: '请输入最低参与人数', trigger: 'blur' },
    { type: 'number', min: 2, message: '最低参与人数不能小于2人', trigger: 'blur' }
  ],
  limitPerUser: [
    { required: true, message: '请输入每人限购数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '限购数量必须大于0', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ]
}

// 禁用过去的日期和当前时间
const disabledDate = (time, type = 'start') => {
  if (type === 'end') {
    // 结束时间不能早于开始时间
    const startTime = groupBuyForm.startTime
    if (startTime) {
      return time.getTime() <= startTime.getTime()
    }
  }
  // 时间不能早于当前时间
  return time.getTime() <= Date.now()
}

// 禁用过去的时间
const disabledTime = (date, type = 'start') => {
  if (!date) return {}
  
  const now = new Date()
  const today = now.toDateString() === date.toDateString()
  
  if (type === 'end' && groupBuyForm.startTime) {
    const isStartDay = date.toDateString() === groupBuyForm.startTime.toDateString()
    if (isStartDay) {
      const start = groupBuyForm.startTime
      return {
        hours: Array.from({ length: 24 }, (_, i) => i).filter(h => h < start.getHours()),
        minutes: date.getHours() === start.getHours() 
          ? Array.from({ length: 60 }, (_, i) => i).filter(m => m <= start.getMinutes())
          : [],
        seconds: date.getHours() === start.getHours() && date.getMinutes() === start.getMinutes()
          ? Array.from({ length: 60 }, (_, i) => i).filter(s => s <= start.getSeconds())
          : []
      }
    }
  }
  
  if (today) {
    return {
      hours: Array.from({ length: 24 }, (_, i) => i).filter(h => h <= now.getHours()),
      minutes: date.getHours() === now.getHours() 
        ? Array.from({ length: 60 }, (_, i) => i).filter(m => m <= now.getMinutes())
        : [],
      seconds: date.getHours() === now.getHours() && date.getMinutes() === now.getMinutes()
        ? Array.from({ length: 60 }, (_, i) => i).filter(s => s <= now.getSeconds())
        : []
    }
  }
  
  return {}
}

// 监听开始时间变化
const watchStartTime = (val) => {
  // 如果结束时间早于开始时间,清空结束时间
  if (groupBuyForm.endTime && val && groupBuyForm.endTime <= val) {
    groupBuyForm.endTime = ''
  }
}

// 在 setup 中添加监听
watch(() => groupBuyForm.startTime, watchStartTime)

// 处理发起团购
const handleStartGroupBuy = (row) => {
  console.log('选中的商品数据:', row)
  
  groupBuyForm.productId = row.id
  groupBuyForm.productName = row.name
  groupBuyForm.productImage = row.image
  groupBuyForm.originalPrice = row.price
  groupBuyForm.groupPrice = row.price * 0.8 // 默认团购价为原价的8折
  groupBuyForm.minCount = 2
  groupBuyForm.limitPerUser = 1
  // 设置默认开始时间为5分钟后
  const now = new Date()
  groupBuyForm.startTime = new Date(now.getTime() + 5 * 60 * 1000)
  // 设置默认结束时间为7天后
  groupBuyForm.endTime = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)
  groupBuyForm.description = `${row.name}团购活动`
  
  console.log('初始化的团购表单数据:', groupBuyForm)
  
  groupBuyDialogVisible.value = true
}

// 提交团购表单
const handleSubmitGroupBuy = async () => {
  if (!groupBuyFormRef.value) return
  
  try {
    await groupBuyFormRef.value.validate()
    
    submitGroupBuyLoading.value = true
    
    // 格式化日期为ISO格式
    const formatDate = (date) => {
      if (!date) return null
      // 转换为ISO格式，保留T分隔符
      const d = new Date(date)
      // 添加8小时以转换为北京时间
      const utc8Date = new Date(d.getTime() + 8 * 60 * 60 * 1000)
      // 格式化为: yyyy-MM-ddTHH:mm:ss
      return utc8Date.toISOString().slice(0, 19)
    }
    
    const submitData = {
      productId: Number(groupBuyForm.productId),
      productName: groupBuyForm.productName,
      productImage: groupBuyForm.productImage,
      originalPrice: Number(groupBuyForm.originalPrice),
      groupPrice: Number(groupBuyForm.groupPrice),
      minCount: Number(groupBuyForm.minCount),
      limitPerUser: Number(groupBuyForm.limitPerUser),
      joinCount: 0,
      status: 0,
      startTime: formatDate(groupBuyForm.startTime),
      endTime: formatDate(groupBuyForm.endTime),
      description: groupBuyForm.description || ''
    }
    
    // 打印提交的数据
    console.log('提交的团购数据:', submitData)
    console.log('时间信息:', {
      原始开始时间: groupBuyForm.startTime,
      转换后开始时间: submitData.startTime,
      原始结束时间: groupBuyForm.endTime,
      转换后结束时间: submitData.endTime
    })
    
    const response = await fetch('/api/group-buys', {
      method: 'POST',
      headers: {
        ...getAuthHeaders(),
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(submitData)
    })
    
    if (!response.ok) {
      const errorText = await response.text()
      console.error('服务器响应错误:', errorText)
      throw new Error(errorText || '创建团购活动失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '创建团购活动失败')
    }
    
    ElMessage.success('创建团购活动成功')
    groupBuyDialogVisible.value = false
    
  } catch (error) {
    console.error('创建团购活动错误:', error)
    ElMessage.error(error.message || '创建团购活动失败，请稍后再试')
  } finally {
    submitGroupBuyLoading.value = false
  }
}

// 页面初始化
onMounted(() => {
  fetchCategories() // 先获取分类数据
  fetchProducts()
  setupResizeListener() // 设置表格高度
  
  // 组件卸载时清理
  return () => {
    cleanupResizeListener();
  };
})
</script>

<style scoped>
.product-container-wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.product-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

:deep(.el-loading-spinner) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-loading-spinner .circular) {
  width: 42px;
  height: 42px;
}

.product-table {
  overflow-y: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .product-container {
    padding: 10px;
  }
  
  .flex-col {
    margin-bottom: 10px;
  }
  
  :deep(.el-table__header) {
    font-size: 12px;
  }
  
  :deep(.el-table__body) {
    font-size: 12px;
  }
  
  :deep(.el-button--small) {
    padding: 6px 10px;
    font-size: 12px;
  }
}

/* 图片上传组件样式优化 */
.image-uploader {
  width: 100%;
  cursor: pointer;
  transition: all 0.3s;
}

.image-preview-container {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.product-image-preview {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
  display: block;
}

.image-uploader-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.image-uploader-empty:hover {
  background-color: #f0f2f5;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.image-uploader-placeholder {
  display: none; /* 移除旧的占位符样式 */
}
</style> 